typo, looks like objectcache need rewrite cause postgresql doesnt have a FROM_UNIXTIM...
[lhc/web/wiklou.git] / includes / DatabasePostgreSQL.php
1 <?php
2 #
3 # DO NOT USE !!! Unless you want to help developping it.
4 #
5 # This file is an attempt to port the mysql database layer to postgreSQL. The
6 # only thing done so far is s/mysql/pg/ and dieing if function haven't been
7 # ported.
8 #
9 # As said brion 07/06/2004 :
10 # "table definitions need to be changed. fulltext index needs to work differently
11 # things that use the last insert id need to be changed. Probably other things
12 # need to be changed. various semantics may be different."
13 #
14 # Hashar
15
16 require_once( "FulltextStoplist.php" );
17 require_once( "CacheManager.php" );
18
19 define( "DB_READ", -1 );
20 define( "DB_WRITE", -2 );
21 define( "DB_LAST", -3 );
22
23 define( "LIST_COMMA", 0 );
24 define( "LIST_AND", 1 );
25 define( "LIST_SET", 2 );
26
27 class Database {
28
29 #------------------------------------------------------------------------------
30 # Variables
31 #------------------------------------------------------------------------------
32 /* private */ var $mLastQuery = "";
33 /* private */ var $mBufferResults = true;
34 /* private */ var $mIgnoreErrors = false;
35
36 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
37 /* private */ var $mOut, $mDebug, $mOpened = false;
38
39 /* private */ var $mFailFunction;
40
41 #------------------------------------------------------------------------------
42 # Accessors
43 #------------------------------------------------------------------------------
44 # Set functions
45 # These set a variable and return the previous state
46
47 # Fail function, takes a Database as a parameter
48 # Set to false for default, 1 for ignore errors
49 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction, $function ); }
50
51 # Output page, used for reporting errors
52 # FALSE means discard output
53 function &setOutputPage( &$out ) { return wfSetRef( $this->mOut, $out ); }
54
55 # Boolean, controls output of large amounts of debug information
56 function setDebug( $debug ) { return wfSetVar( $this->mDebug, $debug ); }
57
58 # Turns buffering of SQL result sets on (true) or off (false). Default is
59 # "on" and it should not be changed without good reasons.
60 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults, $buffer ); }
61
62 # Turns on (false) or off (true) the automatic generation and sending
63 # of a "we're sorry, but there has been a database error" page on
64 # database errors. Default is on (false). When turned off, the
65 # code should use wfLastErrno() and wfLastError() to handle the
66 # situation as appropriate.
67 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors, $ignoreErrors ); }
68
69 # Get functions
70
71 function lastQuery() { return $this->mLastQuery; }
72 function isOpen() { return $this->mOpened; }
73
74 #------------------------------------------------------------------------------
75 # Other functions
76 #------------------------------------------------------------------------------
77
78 function Database()
79 {
80 global $wgOut;
81 # Can't get a reference if it hasn't been set yet
82 if ( !isset( $wgOut ) ) {
83 $wgOut = NULL;
84 }
85 $this->mOut =& $wgOut;
86
87 }
88
89 /* static */ function newFromParams( $server, $user, $password, $dbName,
90 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
91 {
92 $db = new Database;
93 $db->mFailFunction = $failFunction;
94 $db->mIgnoreErrors = $ignoreErrors;
95 $db->mDebug = $debug;
96 $db->mBufferResults = $bufferResults;
97 $db->open( $server, $user, $password, $dbName );
98 return $db;
99 }
100
101 # Usually aborts on failure
102 # If the failFunction is set to a non-zero integer, returns success
103 function open( $server, $user, $password, $dbName )
104 {
105 global $wgEmergencyContact;
106
107 $this->close();
108 $this->mServer = $server;
109 $this->mUser = $user;
110 $this->mPassword = $password;
111 $this->mDBname = $dbName;
112
113 $success = false;
114
115
116 if ( "" != $dbName ) {
117 # start a database connection
118 @$this->mConn = pg_connect("host=$server dbname=$dbName user=$user password=$password");
119 if ( $this->mConn == false ) {
120 wfDebug( "DB connection error\n" );
121 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
122 wfDebug( $this->lastError()."\n" );
123 }
124 }
125 return $this->mConn;
126 }
127
128 # Closes a database connection, if it is open
129 # Returns success, true if already closed
130 function close()
131 {
132 $this->mOpened = false;
133 if ( $this->mConn ) {
134 return pg_close( $this->mConn );
135 } else {
136 return true;
137 }
138 }
139
140 /* private */ function reportConnectionError( $msg = "")
141 {
142 if ( $this->mFailFunction ) {
143 if ( !is_int( $this->mFailFunction ) ) {
144 $this->$mFailFunction( $this );
145 }
146 } else {
147 wfEmergencyAbort( $this );
148 }
149 }
150
151 # Usually aborts on failure
152 # If errors are explicitly ignored, returns success
153 function query( $sql, $fname = "" )
154 {
155 global $wgProfiling;
156
157 if ( $wgProfiling ) {
158 # generalizeSQL will probably cut down the query to reasonable
159 # logging size most of the time. The substr is really just a sanity check.
160 $profName = "query: " . substr( Database::generalizeSQL( $sql ), 0, 255 );
161 wfProfileIn( $profName );
162 }
163
164 $this->mLastQuery = $sql;
165
166 if ( $this->mDebug ) {
167 $sqlx = substr( $sql, 0, 500 );
168 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
169 wfDebug( "SQL: $sqlx\n" );
170 }
171 if( $this->mBufferResults ) {
172 print $sql."<br/>\n";
173 $ret = pg_query( $this->mConn , $sql);
174 } else {
175 // TODO FIXME : php doesnt get a postgre unbuffered query
176 // $ret = mysql_unbuffered_query( $sql, $this->mConn );
177 // I(hashar) am assuming that pg_send_query does the same
178 $ret = pg_send_query( $this->mConn , $sql);
179 }
180
181 if ( false === $ret ) {
182 $error = pg_result_error( $this->mConn );
183 // TODO FIXME : no error number function in postgre
184 // $errno = mysql_errno( $this->mConn );
185 if( $this->mIgnoreErrors ) {
186 wfDebug("SQL ERROR (ignored): " . $error . "\n");
187 } else {
188 wfDebug("SQL ERROR: " . $error . "\n");
189 if ( $this->mOut ) {
190 // this calls wfAbruptExit()
191 $this->mOut->databaseError( $fname, $sql, $error, 0 );
192 }
193 }
194 }
195
196 if ( $wgProfiling ) {
197 wfProfileOut( $profName );
198 }
199 return $ret;
200 }
201
202 function freeResult( $res ) {
203 if ( !@pg_free_result( $res ) ) {
204 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
205 }
206 }
207 function fetchObject( $res ) {
208 @$row = pg_fetch_object( $res );
209 # FIXME: HACK HACK HACK HACK debug
210
211 # TODO:
212 # hashar : not sure if the following test really trigger if the object
213 # fetching failled.
214 if( pg_result_error($this->mConn) ) {
215 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_result_error($this->mConn) ) );
216 }
217 return $row;
218 }
219 function numRows( $res ) {
220 @$n = pg_num_rows( $res );
221 if( pg_result_error($this->mConn) ) {
222 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_result_error($this->mConn) ) );
223 }
224 return $n;
225 }
226 function numFields( $res ) { return pg_num_fields( $res ); }
227 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
228 // TODO FIXME: need to implement something here
229 function insertId() {
230 //return mysql_insert_id( $this->mConn );
231 wfDebugDieBacktrace( "Database::insertId() error : not implemented for postgre" );
232 }
233 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
234 function lastErrno() { return $this->lastError(); }
235 function lastError() { return pg_result_error(); }
236 function affectedRows() { return pg_affected_rows( $this->mConn ); }
237
238 # Simple UPDATE wrapper
239 # Usually aborts on failure
240 # If errors are explicitly ignored, returns success
241 function set( $table, $var, $value, $cond, $fname = "Database::set" )
242 {
243 $sql = "UPDATE \"$table\" SET \"$var\" = '" .
244 wfStrencode( $value ) . "' WHERE ($cond)";
245 return !!$this->query( $sql, DB_WRITE, $fname );
246 }
247
248 # Simple SELECT wrapper, returns a single field, input must be encoded
249 # Usually aborts on failure
250 # If errors are explicitly ignored, returns FALSE on failure
251 function get( $table, $var, $cond, $fname = "Database::get" )
252 {
253 $sql = "SELECT \"$var\" FROM \"$table\" WHERE ($cond)";
254 $result = $this->query( $sql, DB_READ, $fname );
255
256 $ret = "";
257 if ( pg_num_rows( $result ) > 0 ) {
258 $s = pg_fetch_object( $result );
259 $ret = $s->$var;
260 pg_free_result( $result );
261 }
262 return $ret;
263 }
264
265 # More complex SELECT wrapper, single row only
266 # Aborts or returns FALSE on error
267 # Takes an array of selected variables, and a condition map, which is ANDed
268 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
269 # would return an object where $obj->cur_id is the ID of the Astronomy article
270 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
271 {
272 $vars = implode( ",", $vars );
273 $where = Database::makeList( $conds, LIST_AND );
274 $sql = "SELECT \"$vars\" FROM \"$table\" WHERE $where LIMIT 1";
275 $res = $this->query( $sql, $fname );
276 if ( $res === false || !$this->numRows( $res ) ) {
277 return false;
278 }
279 $obj = $this->fetchObject( $res );
280 $this->freeResult( $res );
281 return $obj;
282 }
283
284 # Removes most variables from an SQL query and replaces them with X or N for numbers.
285 # It's only slightly flawed. Don't use for anything important.
286 /* static */ function generalizeSQL( $sql )
287 {
288 # This does the same as the regexp below would do, but in such a way
289 # as to avoid crashing php on some large strings.
290 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
291
292 $sql = str_replace ( "\\\\", "", $sql);
293 $sql = str_replace ( "\\'", "", $sql);
294 $sql = str_replace ( "\\\"", "", $sql);
295 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
296 $sql = preg_replace ('/".*"/s', "'X'", $sql);
297
298 # All newlines, tabs, etc replaced by single space
299 $sql = preg_replace ( "/\s+/", " ", $sql);
300
301 # All numbers => N
302 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
303
304 return $sql;
305 }
306
307 # Determines whether a field exists in a table
308 # Usually aborts on failure
309 # If errors are explicitly ignored, returns NULL on failure
310 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
311 {
312 $res = $this->query( "DESCRIBE '$table'", DB_READ, $fname );
313 if ( !$res ) {
314 return NULL;
315 }
316
317 $found = false;
318
319 while ( $row = $this->fetchObject( $res ) ) {
320 if ( $row->Field == $field ) {
321 $found = true;
322 break;
323 }
324 }
325 return $found;
326 }
327
328 # Determines whether an index exists
329 # Usually aborts on failure
330 # If errors are explicitly ignored, returns NULL on failure
331 function indexExists( $table, $index, $fname = "Database::indexExists" )
332 {
333 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
334 # SHOW INDEX should work for 3.x and up:
335 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
336 // FIXME: hashar : probably need investigation here
337 $sql = "SELECT 'INDEX' FROM '$table'";
338 $res = $this->query( $sql, DB_READ, $fname );
339 if ( !$res ) {
340 return NULL;
341 }
342
343 $found = false;
344
345 while ( $row = $this->fetchObject( $res ) ) {
346 if ( $row->Key_name == $index ) {
347 $found = true;
348 break;
349 }
350 }
351 return $found;
352 }
353
354 function tableExists( $table )
355 {
356 $old = $this->mIgnoreErrors;
357 $this->mIgnoreErrors = true;
358 $res = $this->query( "SELECT 1 FROM '$table' LIMIT 1" );
359 $this->mIgnoreErrors = $old;
360 if( $res ) {
361 $this->freeResult( $res );
362 return true;
363 } else {
364 return false;
365 }
366 }
367
368 function fieldInfo( $table, $field )
369 {
370 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
371 $n = pg_num_fields( $res );
372 for( $i = 0; $i < $n; $i++ ) {
373 // FIXME
374 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
375 $meta = mysql_fetch_field( $res, $i );
376 if( $field == $meta->name ) {
377 return $meta;
378 }
379 }
380 return false;
381 }
382
383 # INSERT wrapper, inserts an array into a table
384 # Keys are field names, values are values
385 # Usually aborts on failure
386 # If errors are explicitly ignored, returns success
387 function insertArray( $table, $a, $fname = "Database::insertArray" )
388 {
389 $sql1 = "INSERT INTO '$table' (";
390 $sql2 = "VALUES (" . Database::makeList( $a );
391 $first = true;
392 foreach ( $a as $field => $value ) {
393 if ( !$first ) {
394 $sql1 .= ",";
395 }
396 $first = false;
397 $sql1 .= $field;
398 }
399 $sql = "$sql1) $sql2)";
400 return !!$this->query( $sql, $fname );
401 }
402
403 # A cross between insertArray and getArray, takes a condition array and a SET array
404 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
405 {
406 $sql = "UPDATE '$table' SET " . $this->makeList( $values, LIST_SET );
407 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
408 $this->query( $sql, $fname );
409 }
410
411 # Makes a wfStrencoded list from an array
412 # $mode: LIST_COMMA - comma separated, no field names
413 # LIST_AND - ANDed WHERE clause (without the WHERE)
414 # LIST_SET - comma separated with field names, like a SET clause
415 /* static */ function makeList( $a, $mode = LIST_COMMA )
416 {
417 $first = true;
418 $list = "";
419 foreach ( $a as $field => $value ) {
420 if ( !$first ) {
421 if ( $mode == LIST_AND ) {
422 $list .= " AND ";
423 } else {
424 $list .= ",";
425 }
426 } else {
427 $first = false;
428 }
429 if ( $mode == LIST_AND || $mode == LIST_SET ) {
430 $list .= "$field=";
431 }
432 if ( !is_numeric( $value ) ) {
433 $list .= "'" . wfStrencode( $value ) . "'";
434 } else {
435 $list .= $value;
436 }
437 }
438 return $list;
439 }
440
441 function startTimer( $timeout )
442 {
443 global $IP;
444 wfDebugDieBacktrace( "Database::startTimer() error : mysql_thread_id() not implemented for postgre" );
445 $tid = mysql_thread_id( $this->mConn );
446 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
447 }
448
449 function stopTimer()
450 {
451 }
452
453 }
454
455 #------------------------------------------------------------------------------
456 # Global functions
457 #------------------------------------------------------------------------------
458
459 /* Standard fail function, called by default when a connection cannot be established
460 Displays the file cache if possible */
461 function wfEmergencyAbort( &$conn ) {
462 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
463
464 header( "Content-type: text/html; charset=$wgOutputEncoding" );
465 $msg = $wgSiteNotice;
466 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
467 $text = $msg;
468
469 if($wgUseFileCache) {
470 if($wgTitle) {
471 $t =& $wgTitle;
472 } else {
473 if($title) {
474 $t = Title::newFromURL( $title );
475 } elseif (@$_REQUEST['search']) {
476 $search = $_REQUEST['search'];
477 echo wfMsgNoDB( "searchdisabled" );
478 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
479 wfAbruptExit();
480 } else {
481 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
482 }
483 }
484
485 $cache = new CacheManager( $t );
486 if( $cache->isFileCached() ) {
487 $msg = "<p style='color: red'><b>$msg<br />\n" .
488 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
489
490 $tag = "<div id='article'>";
491 $text = str_replace(
492 $tag,
493 $tag . $msg,
494 $cache->fetchPageText() );
495 }
496 }
497
498 /* Don't cache error pages! They cause no end of trouble... */
499 header( "Cache-control: none" );
500 header( "Pragma: nocache" );
501 echo $text;
502 wfAbruptExit();
503 }
504
505 function wfStrencode( $s )
506 {
507 return addslashes( $s );
508 }
509
510 # Ideally we'd be using actual time fields in the db
511 function wfTimestamp2Unix( $ts ) {
512 return gmmktime( ( (int)substr( $ts, 8, 2) ),
513 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
514 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
515 (int)substr( $ts, 0, 4 ) );
516 }
517
518 function wfUnix2Timestamp( $unixtime ) {
519 return gmdate( "YmdHis", $unixtime );
520 }
521
522 function wfTimestampNow() {
523 # return NOW
524 return gmdate( "YmdHis" );
525 }
526
527 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
528 function wfInvertTimestamp( $ts ) {
529 return strtr(
530 $ts,
531 "0123456789",
532 "9876543210"
533 );
534 }
535 ?>